<template>
  <div class="table-container">
    <!--
      <el-table :data="comTableData">
      <el-table-column v-for=""></el-table-column>
    </el-table>
    -->
    <vxe-table
      v-loading="loading"
      element-loading-text="数据加载中"
      element-loading-spinner="el-icon-loading"
      :data="tableData"
      height="280"
      style="width: 100%"
      :edit-config="{
        trigger: 'dblclick',
        mode: 'row',
        activeMethod: activeRowMethod,
      }"
      @edit-disabled="editDisabledEvent"
    >
      <vxe-table-column
        fixed="left"
        width="200"
        field="opt"
        title="项目"
      ></vxe-table-column>
      <vxe-table-column
        width="200"
        v-for="(col, index) in cols"
        :key="index"
        :field="col.field"
        :title="col.title"
        :edit-render="{ name: 'input' }"
      >
      </vxe-table-column>
    </vxe-table>
    <el-input-number
      v-model="num"
      controls-position="right"
      @change="handleChange"
      :min="1"
    ></el-input-number>
    <el-button type="primary" @click="save">设置故障</el-button>
    <el-button @click="recovery">恢复故障</el-button>
  </div>
</template>

<script>
export default {
  name: "commTable",
  data() {
    return {
      tableData: [
        { opt: "id", val1: "" },
        {
          opt: "电能表/交流采样装置序号",
          val1: "1",
        },
        {
          opt: "所属测量点号",
          val1: "1",
        },
        {
          opt: "通信端口号",
          val1: "4",
        },
        {
          opt: "通讯波特率",
          val1: "3",
        },
        {
          opt: "通信规约类型",
          val1: "30",
        },
        {
          opt: "通信地址",
          val1: "AAAAAAAAAAAA",
        },
        {
          opt: "所属采集器通信地址",
          val1: "000000000000",
        },
      ],
      loading: false,
      cols: [{ field: "val1", title: "表1" }],
      num: "1",
    };
  },
  mounted() {
    this.tsearch();
  },
  methods: {
    handleChange(currentValue, oldValue) {
      if (currentValue > oldValue) {
        this.cols = [{ field: "val1", title: "表1" }];
        let i = currentValue - 1;
        var obj, tv, key, k;
        for (let n = 0; n < i; n++) {
          obj = {
            field: "val" + Number(n + 2),
            title: "表" + Number(n + 2),
          };
          this.cols.push(obj);
        }
        let karr = [];
        for (k = oldValue; k < this.cols.length; k++) {
          key = this.cols[k].field;
          karr.push((Number(k) + 1).toString());
          for (let j in this.tableData) {
            if (j == 0) {
              this.tableData[j][key] = null;
            } else if (j == 1 || j == 2) {
              this.tableData[j][key] = (Number(k) + 1).toString();
            } else if (j == 3) {
              this.tableData[j][key] = "4";
            } else if (j == 4) {
              this.tableData[j][key] = "3";
            } else if (j == 5) {
              this.tableData[j][key] = "30";
            } else if (j == 6) {
              this.tableData[j][key] = "AAAAAAAAAAAA";
            } else if ((j = 7)) {
              this.tableData[j][key] = "000000000000";
            }
          }
        }
        // console.log(this.tableData);
      } else {
        let i = oldValue - currentValue;
        var obj, tv, key, k;
        for (let n = 0; n < i; n++) {
          obj = {
            // prop: 'value' + Number(oldValue - 3),
            title: "表" + Number(oldValue - 2),
          };
          this.cols.pop();
        }
        let keyarr = [];
        for (k = 0; k < this.cols.length; k++) {
          key = this.cols[k].field;
          keyarr.push(key);
        }
        keyarr.push("opt");
        for (let j in this.tableData) {
          function del(obj, keys) {
            keys.map(function (key) {
              delete obj[key];
            });
            return obj;
          }
          this.tableData[j] = del(
            this.tableData[j],
            Object.keys(this.tableData[j]).filter(
              (key) => !keyarr.includes(key)
            )
          );
        }
      }
    },
    save() {
      this.loading = true;
      var tarr = [];
      for (let i in this.tableData) {
        delete this.tableData[i].opt;
        delete this.tableData[i]._XID;
        tarr.push(Object.values(this.tableData[i]));
      }
      var keyarr = [
        "id",
        "testPointNumber",
        "serialNumber",
        "requestPort",
        "requestBaudRate",
        "communicationProtocolType",
        "requestAddress",
        "connPwd",
      ];
      var objarr = [];
      for (let j in tarr[0]) {
        objarr.push({});
      }
      for (let n in tarr) {
        for (let j in tarr[n]) {
          objarr[j][keyarr[n]] = tarr[n][j];
        }
      }
      // console.log(objarr)
      // objarr.push({ id: this.lbdeviceId })
      this.$axios
        .post(
          this.$URL + "/SFault/JzqTestParm",
          // this.$qs.stringify(
          //   { id: this.lbdeviceId },
          //   { indices: false }
          // )
          { id: 3, datas: objarr },
          { indices: false }
        )
        .then((res) => {
          if (res.data.code === 0) {
            // this.num = objarr.length
            // var optarr = [
            //   'id',
            //   '电能表/交流采样装置序号',
            //   '所属测量点号',
            //   '通信端口号',
            //   '通讯波特率',
            //   '通信规约类型',
            //   '通信地址',
            //   '所属采集器通信地址'
            // ]
            // var obj, param, opt
            // var objarr1 = []
            // this.cols = []
            // this.cols.splice(this.cols.findIndex(item => item.title === '表1'))
            // for (let n in objarr) {
            //   var coli = {}
            //   coli.opt = optarr[n]
            //   coli['field'] = 'val' + (Number(n) + 1)
            //   coli['title'] = '表' + (Number(n) + 1)
            //   this.cols.push(coli)
            //   param = (({
            //     id,
            //     testPointNumber,
            //     serialNumber,
            //     requestPort,
            //     requestBaudRate,
            //     communicationProtocolType,
            //     requestAddress,
            //     connPwd
            //   }) => ({
            //     id,
            //     testPointNumber,
            //     serialNumber,
            //     requestPort,
            //     requestBaudRate,
            //     communicationProtocolType,
            //     requestAddress,
            //     connPwd
            //   }))(objarr[n])
            //   var dataNum = 0
            //   for (let i in param) {
            //     this.tableData[dataNum]['opt'] = optarr[dataNum]
            //     this.tableData[dataNum]['val' + (Number(n) + 1)] = param[i]
            //     dataNum++
            //   }
            //   this.loading = false
            // }
            for (let i in objarr) {
              (objarr[i].type = 1), (objarr[i].sDeviceId = 3);
            }
            this.$axios
              .post(
                this.$URL + "/STerminalTestParameter/add",
                {
                  id: 3,
                  list: objarr,
                },
                { arrayFormat: "indices" }
              )
              .then((res) => {
                // console.log(objarr)
                this.tsearch();
              });
          }
        })
        .catch((err) => {
          this.loading = false;
          this.$notify({
            type: "error",
            message: "获取失败",
            position: "bottom-right",
          });
        });
    },

    recovery() {
      this.loading = true;
      this.$axios
        .post(
          this.$URL + "/STerminalTestParameter/list",
          this.$qs.stringify({
            deviceId: 3,
            type: 0,
          })
        )
        .then((res) => {
          if (res.data.code === 0) {
            this.num = res.data.data.length;
            var optarr = [
              "id",
              "电能表/交流采样装置序号",
              "所属测量点号",
              "通信端口号",
              "通讯波特率",
              "通信规约类型",
              "通信地址",
              "所属采集器通信地址",
            ];
            var obj, param, opt;
            var obarr = [];
            this.cols.splice(
              this.cols.findIndex((item) => item.title === "表1")
            );
            // for (let j in optarr) {
            //   this.cols.opt = optarr[j]
            // }
            for (let n in res.data.data) {
              var coli = {};
              coli.opt = optarr[n];
              coli["field"] = "val" + (Number(n) + 1);
              coli["title"] = "表" + (Number(n) + 1);
              this.cols.push(coli);
              param = (({
                id,
                testPointNumber,
                serialNumber,
                requestPort,
                requestBaudRate,
                communicationProtocolType,
                requestAddress,
                connPwd,
              }) => ({
                id,
                testPointNumber,
                serialNumber,
                requestPort,
                requestBaudRate,
                communicationProtocolType,
                requestAddress,
                connPwd,
              }))(res.data.data[n]);
              var dataNum = 0;
              for (let i in param) {
                this.tableData[dataNum]["opt"] = optarr[dataNum];
                this.tableData[dataNum]["val" + (Number(n) + 1)] = param[i];
                dataNum++;
              }
            }
            this.loading = false;
            this.$axios
              .post(
                this.$URL + "/SFault/JzqTestParm",

                { id: 3, datas: res.data.data },
                { indices: false }
              )
              .then((res) => {
                // console.log(res.data.data);
              });
          }
        })
        .catch((err) => {
          this.loading = false;
          this.$notify({
            type: "error",
            message: "获取失败",
            position: "bottom-right",
          });
        });
    },
    tsearch() {
      this.loading = true;
      this.$axios
        .post(
          this.$URL + "/STerminalTestParameter/list",
          this.$qs.stringify({
            deviceId: 3,
            type: 1,
          })
        )
        .then((res) => {
          if (res.data.code === 0) {
            if (res.data.data.length <= 0) {
              this.tableData = this.tableData;
              this.loading = false;
            } else {
              this.num = res.data.data.length;
              // console.log(this.num);
              var optarr = [
                "id",
                "电能表/交流采样装置序号",
                "所属测量点号",
                "通信端口号",
                "通讯波特率",
                "通信规约类型",
                "通信地址",
                "所属采集器通信地址",
              ];
              var obj, param, opt;
              var obarr = [];
              // console.log(this.cols);
              this.cols.splice(
                this.cols.findIndex((item) => item.title === "表1")
              );
              // console.log(this.cols)
              // this.cols.push({ opt: '项目' })
              // for (let n in res.data.data) {
              for (let n in res.data.data) {
                var coli = {};
                coli["field"] = "val" + (Number(n) + 1);
                coli["title"] = "表" + (Number(n) + 1);
                this.cols.push(coli);

                param = (({
                  id,
                  testPointNumber,
                  serialNumber,
                  requestPort,
                  requestBaudRate,
                  communicationProtocolType,
                  requestAddress,
                  connPwd,
                }) => ({
                  id,
                  testPointNumber,
                  serialNumber,
                  requestPort,
                  requestBaudRate,
                  communicationProtocolType,
                  requestAddress,
                  connPwd,
                }))(res.data.data[n]);
                // console.log(param);
                var dataNum = 0;
                for (let i in param) {
                  this.tableData[dataNum]["opt"] = optarr[dataNum];
                  this.tableData[dataNum]["val" + (Number(n) + 1)] = param[i];
                  dataNum++;
                }
              }
              this.loading = false;
            }
          }
        })
        .catch((err) => {
          this.loading = false;
          this.$notify({
            type: "error",
            message: "获取失败",
            position: "bottom-right",
          });
        });
    },
    activeRowMethod({ row, rowIndex }) {
      return rowIndex !== 0;
    },
    editDisabledEvent({ row, column }) {
      // console.log(row, column);
    },
  },
};
</script>

<style lang="scss" scoped>
.table-container {
  width: 100%;
  height: 100%;
}
</style>
